package com.webservice.ftp.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

/**
 * COPYRIGHT (C) 2010 CORPRATION All Rights Reserved User: huangbin_1 Date:
 * 14-3-24 Time: 下午4:24 用途:转化加密文件为非加密的文件
 */
public class ConvertFTPXMLFile {

	/**
	 * 主函数
	 * 
	 * @param args
	 *            参数 1)源文件 2)目标文件 3) ftp.aesKey 4) ftp.messageKey 5)
	 *            ftp.aesOffsets 6) hashTypeCount
	 */
	static public void main(String[] args) {
		System.out.println("args = [" + args.length + "]");
		if (args.length == 2 || args.length == 6) {

		} else {
			System.out.println("args \n" + "1)src xml file\n"
					+ "2)target xml file\n" + "3)ftp.aesKey\n"
					+ "4) ftp.messageKey\n" + "5) ftp.aesOffsets\n"
					+ "6) hashTypeCount");
			return;
		}
		String srcFilename = args[0];
		String targetFilename = args[1];
		System.out.println("srcFilename = [" + srcFilename + "]");
		System.out.println("targetFilename = [" + targetFilename + "]");

		String aesKey = "LVVKVXWF56496929";
		String messageKey = "LLX239";
		String aesOffsets = "MSFBUWFS86537785";
		String hashcode = "2";
		if (args.length == 6) {
			aesKey = args[2];
			messageKey = args[3];
			aesOffsets = args[4];
			hashcode = args[5];
		}

		File srcfile = new File(srcFilename);
		if (!srcfile.exists()) {
			System.out.println("srcfile " + srcFilename + " not exists.");
			return;
		}
		String content = ConvertFTPXMLFile.readFile(srcfile);
		System.out.println("content = " + content);
		System.out.println("aesKey = " + aesKey);
		System.out.println("aesOffsets = " + aesOffsets);
		System.out.println("hashcode = " + hashcode);
		System.out.println("messageKey = " + messageKey);
		String xmlData = new FtpDataOper().ftpFileOper(content, aesKey,
				aesOffsets, hashcode, messageKey);
		System.out.println("xmlData = " + xmlData);

		ConvertFTPXMLFile.writeFile(new File(targetFilename), xmlData);
	}

	/**
	 * 写文件的方法
	 * 
	 * @param file
	 *            目标文件
	 * @param content
	 *            文件内容
	 * @return 是否正常写文件
	 */
	static public boolean writeFile(File file, String content) {
		boolean r = false;
		try {
			file.createNewFile();
			FileWriter fileWriter = new FileWriter(file);
			fileWriter.write(content);
			fileWriter.close();
			r = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return r;
	}

	/**
	 * 读取 xml 文件内容
	 * 
	 * @param file
	 *            文件名
	 * @return 文件内容
	 */
	static public String readFile(File file) {
		StringBuffer sb = new StringBuffer();

		try {
			FileInputStream fis = new FileInputStream(file);
			byte[] buf = new byte[1024];
			while ((fis.read(buf)) != -1) {
				sb.append(new String(buf));
				buf = new byte[1024];// 重新生成，避免和上次读取的数据重复
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
